import { connect, history } from 'umi';
import { Button, Card, Space, Spin, message, Form, TreeSelect } from 'antd';
import { useEffect, useContext, useState, useMemo } from 'react';

import moment from 'moment';
import { SendOutlined, DiffOutlined, SearchOutlined, RollbackOutlined } from '@ant-design/icons';

import {
  getDeptPosTreeIcon,
  getInvoiceCode,
  getKeyRouter,
  getPersonalInfo,
  getPosIDs,
  getPosName,
  getTenantID,
  getUserDepName,
  getUserID,
  getUserName,
} from '@/utils';
import pageStyles from '@/common/pageLayout.less';
import ScrollBarLayout from '@/components/ScrollBarLayout';
import { Descriptions, useDescriptions } from '@/components/Descriptions';

import { ApplyUpdateContext } from '../common/ApplyContext';
import { WorkflowChedkRecord, WorkflowSwitchModal, WorkflowNoDefaultTable, WorkflowHndTaskBtn } from '@/components/WorkflowCommonCopy';
import { AddDisclosureServices, EditDisclosureServices, GetDetailDisclosureServices, updateApplyFlagServices } from '../services/UpdateService';
import {
  YXGK_STATE_QC,
  YXGK_STATE_SHZ,
  YXGK_STATE_ZF,
  businessCategory,
  flowBusinessType,
  formatDecimal,
  orderType,
  requestController,
} from '../common/Format';
import { closeCurrent, renderFileFunc, SHTH_CHECKSTATE, SHZ_CHECKSTATE } from '../../Acommon';
import { UpdateIntentModal } from './UpdateIntentModal';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import { ILoadMapTypeAll } from '@/common';
import { UploadFormCommon } from '@/components/UploadForm';
import { getFlowOrgTreeByOrgID, getFlowOrgTreeByOrgIDService, getPosTreeByDetIDService, getUserDataList } from '@/services/BaseLayout';
import { DescriptionsType, useDescriptionsType } from '@/components/DescriptionsType';

/**
 * @UpdateIntent 意向公开单
 * @returns
 */
const UpdateIntent: React.FC<any> = ({ locationProps, curRes }) => {
  const { info, operateType, type } = locationProps?.state || {}; //路由
  const { prefixCls } = useContext(ApplyUpdateContext); //上下文
  const [resObj, setResObj] = useState<Record<string, any>>({}); //详情对象
  const [ProjectModal, setProjectModal] = useState<Record<string, any>>({}); //是否显示选择采购项目弹窗
  const [project, setProject] = useState<Record<string, any>>({});
  const [changeFromRef] = Form.useForm(); // 表单实例
  // const [uploadUrl, setUploadUrl] = useState<string>(''); // 存储上传的文件地址【表单获取不到-未排查到原因】
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); // 撤销弹窗
  const [flagLoading, setFlagLoading] = useState<boolean>(false);
  const [isSHTGFlag, setIsSHTGFlag] = useState(false); // 审核中，审核通过/作废 开关

  // 请求获取 - 部门数据
  const [deptData, setDeptData] = useState<Record<string, any>[]>([]);

  // 请求获取 - 岗位数据
  const [postData, setPostData] = useState<Record<string, any>[]>([]);

  // 请求获取 - 人员数据
  const [userData, setUserData] = useState<Record<string, any>[]>([]);

  // 工作流
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  /** 是否可以编辑 */
  const isEditState = useMemo(() => {
    if (type == 'view') return false;
    if (!resObj?.id && curRes?.['/purchaseSourceIntentController/add']) {
      return true;
    } else if (
      resObj?.id &&
      !resObj?.checkState &&
      curRes?.['/purchaseSourceIntentController/edit'] &&
      resObj?.createPositionID == getPosIDs() &&
      resObj?.createrID == getUserID()
    ) {
      return true;
    } else if (
      resObj?.id &&
      resObj?.state == YXGK_STATE_SHZ() &&
      resObj?.checkState == SHTH_CHECKSTATE() &&
      resObj?.applyPositionID == getPosIDs() &&
      resObj?.applyerID == getUserID() &&
      curRes?.['/purchaseSourceIntentController/edit']
    ) {
      return true;
    } else {
      return false;
    }
  }, [resObj, curRes]);

  /** 详情接口 */
  const { GetDetailDisclosureRun, GetDetailDisclosureLoading } = GetDetailDisclosureServices((res) => {
    if (res?.msgFlag) {
      let resObj = res?.obj;
      message?.success(res?.msg);
      setFlagLoading(false);
      setResObj(resObj);

      // setProject({
      //   applyID: resObj?.applyID,
      //   purchProjectCode: resObj?.purchProjectCode,
      //   purchProjectName: resObj?.purchProjectName,
      // });
      // setUploadUrl(resObj?.attachURL);
      // setFieldsValue({
      //   applyTitle: resObj?.purchProjectName,
      //   intentCode: resObj?.intentCode,
      //   applyTime: moment(resObj?.applyTime).format('YYYY-MM-DD'),
      //   expectTime: moment(resObj?.expectTime),
      //   expectSum: formatDecimal(resObj?.expectSum),
      //   purchaseInfo: resObj?.purchaseInfo,
      //   applyerName: resObj?.applyerName,
      //   applyDepartmentName: resObj?.applyDepartmentName,
      //   applyPositionName: resObj?.applyPositionName,
      //   applyPhone: resObj?.applyPhone,
      //   remark: resObj?.remark,
      //   attachURL: resObj?.attachURL,
      // });

      // getPostionByDeptID(resObj?.applyDepartmentID)
      // getUserByPosID(resObj?.applyPositionID)

      getPosTreeRun({ params: 1, flowType: 'null', orgID: resObj?.applyDepartmentID })?.then((res) => {
        if (res?.obj && res?.msgFlag) {
          let PostDatas = res?.obj?.[0]?.children || [];
          setPostData(PostDatas); // 更新岗位数据
        }
      });

      getUserRun({ userPositionID: resObj?.applyPositionID })?.then((res) => {
        if (res?.rows && res?.msgFlag) {
          let userDatas = res?.rows || [];
          setUserData(userDatas); // 更新人员数据
        }
      });

      setFieldsValue({
        ...resObj,
        applyTime: moment(resObj?.applyTime).format('YYYY-MM-DD'),
        expectTime: moment(resObj?.expectTime),
        expectSum: formatDecimal(resObj?.expectSum),
      });
    }
  });

  /** 添加接口 */
  const { AddDisclosureRun, AddDisclosureLoading } = AddDisclosureServices((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
      if (res?.obj) GetDetailDisclosureRun({ id: res?.obj });
    }
  });

  /** 编辑接口 */
  const { EditDisclosureRun, EditDisclosureLoading } = EditDisclosureServices((res) => {
    if (res?.msgFlag) {
      message?.success(res?.msg);
      if (res?.obj) GetDetailDisclosureRun({ id: res?.obj });
    }
  });

  /** 修改申请是否 意向公开/招标采购代表 */
  const { updateApplyFlagRun, updateApplyFlagLoading } = updateApplyFlagServices((res) => {
    if (res?.msgFlag) {
      message.success(res?.msg);
    } else {
      message.error(res?.msg);
    }
  });

  /** 获取业务部门数据 */
  const { getFlowOrgTreeRun, getFlowOrgTreeLoading, getFlowOrgList } = getFlowOrgTreeByOrgIDService();

  /** 根据部门获取岗位 */
  const { getPosTreeRun, getPosTreeLoading } = getPosTreeByDetIDService(() => {});

  /** 根据岗位获取人员 */
  const { getUserRun, getUserLoading, getUserList, pramsObjInfo } = getUserDataList(() => {});

  //

  /** 提交 */
  const submit = (flag) => {
    if (type === 'view' && flag) {
      setWorkFlowInfoObj({
        selectFlowRows: resObj,
        showWorkFlowModal: true,
        saveNoDefaultFlowID: '',
      });
      return;
    }

    validateFields()?.then(
      (formVal) => {
        let formResObj = {
          ...formVal,
          expectTime: moment(formVal?.expectTime)?.format('YYYY-MM-DD HH:mm:ss'),
          applyTime: moment(new Date())?.format('YYYY-MM-DD HH:mm:ss'),
          state: YXGK_STATE_QC(),
          businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`,
          // ...val,
          // purchProjectName: val?.applyTitle,
          // purchProjectCode: val?.intentCode,
          // expectTime: moment(val?.expectTime)?.format('YYYY-MM-DD HH:mm:ss'),
          // applyTime: moment(new Date())?.format('YYYY-MM-DD HH:mm:ss'),
          // state: YXGK_STATE_QC(),
          // businessType: `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`,
          // attachURL: uploadUrl,
          // ...project,
        };

        //判断是新增还是编辑
        if (resObj?.id) {
          let { id, versionNum } = resObj;
          let editParams = { id, versionNum, ...formResObj };
          EditDisclosureRun(editParams)?.then((res) => {
            if (res?.msgFlag && flag) {
              setWorkFlowInfoObj({
                selectFlowRows: editParams,
                showWorkFlowModal: true,
                saveNoDefaultFlowID: '',
              });
            }
          });
          return true;
        } else {
          let addParams = { ...formResObj };
          AddDisclosureRun(addParams)?.then((res) => {
            if (res?.msgFlag && flag) {
              setWorkFlowInfoObj({
                selectFlowRows: { ...addParams, id: res?.obj },
                showWorkFlowModal: true,
                saveNoDefaultFlowID: '',
              });
            }
          });
        }
      },
      () => {
        message?.warning('请将意向公开申请补充完整！');
      },
    );
  };

  /** 初始请求 */
  useEffect(() => {
    // 根据当前人获取组织机构
    getFlowOrgTreeRun({ params: 0, flowType: 'null' })?.then((res) => {
      if (res?.obj && res?.msgFlag) {
        setDeptData(res?.obj);
      }
    });
  }, []);

  /** 监听数据状态改变，更改状态 */
  // useEffect(() => {
  //   if (
  //     (resObj?.state && resObj?.state == `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1001` && resObj?.checkState == SHZ_CHECKSTATE()) ||
  //     (resObj?.state == `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1000` && resObj?.checkState == SHTH_CHECKSTATE())
  //   ) {
  //     setIsSHTGFlag(true);
  //   }
  //   if (
  //     isSHTGFlag &&
  //     (resObj?.state == `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1004` || resObj?.state == `${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1003`)
  //   ) {
  //     // 修改申请状态
  //     updateApplyFlagRun({
  //       expertID: null,
  //       expertFlag: null,
  //       intentID: resObj?.id,
  //       intentFlag: 0,
  //     });
  //   }
  // }, [resObj?.state, resObj?.checkState]);

  /** 回显数据 [TODO: 后续拿包id查包详情] */
  useEffect(() => {
    if (info?.mpurchaseSourceIntents?.[0]?.id) {
      GetDetailDisclosureRun({ id: info?.mpurchaseSourceIntents?.[0]?.id });
    } else {
      // setFieldsValue({
      //   applyTitle: info?.applyTitle,
      //   applyTime: moment(info?.applyTime).format('YYYY-MM-DD'),
      //   applyType: moment(info?.applyType).format('YYYY-MM-DD'),
      //   applyerName: getUserName(),
      //   applyDepartmentName: getUserDepName(),
      //   applyPositionName: getPosName(),
      //   applyPhone: getPersonalInfo()?.phoneMobile || '',
      // });
    }
  }, [info, operateType]);

  /**处理数据去掉岗位*/
  const handleNotPostion = (treeData: Record<string, any>[]) => {
    const loopTree = (dataList: Record<string, any>[]) => {
      dataList?.forEach((item: any, index: number) => {
        if (item?.textType == '0' || item?.textType == '1') {
          const childrenList: Record<string, any>[] = item?.children?.filter((itemChil: any) => itemChil?.textType == '0' || itemChil?.textType == '1');
          dataList[index] = {
            ...item,
            title: (
              <span>
                {getDeptPosTreeIcon(String(item?.textType))}
                {item?.text}
              </span>
            ),
            children: childrenList?.length > 0 ? loopTree(childrenList) : null,
            disabled: item?.textType == '0' ? true : false,
            // disabled: item?.dutyPositionID ? false : true
          };
        }
      });
      return dataList;
    };

    const treeList: Record<string, any>[] = loopTree(treeData);
    return treeList;
  };

  /**岗位数据处理*/
  const handleNPostion = (treeData: Record<string, any>[]) => {
    const loopTree = (dataList: Record<string, any>[]) => {
      dataList?.forEach((item: any, index: number) => {
        const childrenList: Record<string, any>[] = item?.children?.filter((itemChil: any) => itemChil?.textType == '2');
        dataList[index] = {
          ...item,
          title: (
            <span>
              {getDeptPosTreeIcon(String(item?.textType))}
              {item?.text}
            </span>
          ),
          children: childrenList?.length > 0 ? loopTree(childrenList) : null,
          disabled: item?.textType == '1' ? true : false,
          // disabled: item?.dutyPositionID ? false : true
        };
      });
      return dataList;
    };

    const treeList: Record<string, any>[] = loopTree(treeData);
    return treeList;
  };

  /**人员数据处理*/
  const handleUser = (treeData: Record<string, any>[]) => {
    const loopTree = (dataList: Record<string, any>[]) => {
      dataList?.forEach((item: any, index: number) => {
        const childrenList: Record<string, any>[] = item?.children?.filter((itemChil: any) => itemChil?.textType == '2');
        dataList[index] = {
          ...item,
          title: (
            <span>
              {getDeptPosTreeIcon(String(item?.textType))}
              {item?.realName}
            </span>
          ),
          children: childrenList?.length > 0 ? loopTree(childrenList) : null,
          // disabled: item?.textType == '0' ? true : false,
          // disabled: item?.dutyPositionID ? false : true
        };
      });
      return dataList;
    };

    const treeList: Record<string, any>[] = loopTree(treeData);
    return treeList;
  };

  // 根据部门ID获取岗位数据方法
  const getPostionByDeptID = async (deptID: string) => {
    getPosTreeRun({ params: 1, flowType: 'null', orgID: deptID })?.then((res) => {
      if (res?.obj && res?.msgFlag) {
        let PostDatas = res?.obj?.[0]?.children || [];
        setFieldsValue({ applyPositionID: null, applyerID: null, applyPhone: null });
        setPostData(PostDatas); // 更新岗位数据
        setUserData([]); // 人员数据清空
      }
    });
  };

  // 根据岗位ID获取人员数据方法
  const getUserByPosID = async (posID: string) => {
    getUserRun({ userPositionID: posID })?.then((res) => {
      if (res?.rows && res?.msgFlag) {
        let userDatas = res?.rows || [];
        if (userDatas?.length == 1) {
          setFieldsValue({ applyerID: userDatas?.[0]?.id, applyPhone: userDatas?.[0]?.phoneMobile });
        } else if (userDatas?.length == 0) {
          setFieldsValue({ applyerID: null, applyPhone: null });
        }
        setUserData(userDatas);
      }
    });
  };

  /** 表格表单配置信息 */
  const [config, { setFieldsValue, validateFields }] = useDescriptionsType({
    labelWidth: 180,
    basicForm: changeFromRef,
    schemas: [
      {
        key: 'applyIntentTitle',
        title: '意向公开申请',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'applyTime',
            component: 'Input',
            placeholder: '自动带出',
            initialValue: moment(new Date()).format('YYYY-MM-DD'),
            disabled: true,
            required: false,
          },
          {
            label: '流水单号',
            field: 'intentCode',
            component: 'Input',
            placeholder: '自动带出',
            initialValue: getInvoiceCode('YX'),
            disabled: true,
          },
          {
            label: '申请部门/单位',
            field: 'applyDepartmentID',
            component: 'TreeSelect',
            loading: getFlowOrgTreeLoading,
            placeholder: '请选择',
            treeData: handleNotPostion(deptData),
            disabled: !isEditState || resObj?.checkState ? true : false,
            showArrow: !isEditState || resObj?.checkState ? false : true,
            fieldNames: { label: 'title', value: 'id', children: 'children' } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            onSelect: getPostionByDeptID,
            // component: 'Render',
            // render: (text) => {
            //   if (!isEditState) {
            //     return <span>{text || '--'}</span>;
            //   } else {
            //     return (
            //       <TreeSelect
            //         loading={getFlowOrgTreeLoading}
            //         placeholder="请选择"
            //         treeData={handleNotPostion(deptData)}
            //         disabled={!isEditState || resObj?.checkState ? true : false}
            //         showArrow={!isEditState || resObj?.checkState ? false : true}
            //         fieldNames={{
            //           label: 'title',
            //           value: 'id',
            //           children: 'children',
            //         }}
            //         showSearch={true}
            //         treeNodeFilterProp={'text'}
            //         allowClear={true}
            //         onSelect={async (value, node) => {
            //           getPosTreeRun({ params: 1, flowType: 'null', orgID: value })?.then((res) => {
            //             if (res?.obj && res?.msgFlag) {
            //               let PostDatas = res?.obj?.[0]?.children || [];
            //               setFieldsValue({ applyPositionID: null, applyerID: null, applyPhone: null })
            //               setPostData(PostDatas) // 更新岗位数据
            //               setUserData([]) // 人员数据清空
            //             }
            //           })
            //         }}
            //       />
            //     );
            //   }
            // },
            // disabled: true,
          },
          {
            label: '职务岗位',
            field: 'applyPositionID',
            component: 'TreeSelect',
            loading: getPosTreeLoading,
            placeholder: '请选择',
            treeData: handleNPostion(postData),
            disabled: !isEditState || resObj?.checkState ? true : false,
            showArrow: !isEditState || resObj?.checkState ? false : true,
            fieldNames: { label: 'title', value: 'id' } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            onSelect: getUserByPosID,
            // component: 'Render',
            // placeholder: '自动带出',
            // // disabled: true,
            // render: (text) => {
            //   if (!isEditState) {
            //     return <span>{text || '--'}</span>;
            //   } else {
            //     return (
            //       <TreeSelect
            //         loading={getPosTreeLoading}
            //         placeholder="请选择"
            //         treeData={handleNPostion(postData)}
            //         disabled={!isEditState || resObj?.checkState ? true : false}
            //         showArrow={!isEditState || resObj?.checkState ? false : true}
            //         fieldNames={{
            //           label: 'title',
            //           value: 'id',
            //         }}
            //         showSearch={true}
            //         treeNodeFilterProp={'text'}
            //         treeIcon={true}
            //         onSelect={(value, node) => {
            //           getUserRun({ userPositionID: value })?.then((res) => {
            //             if (res?.rows && res?.msgFlag) {
            //               let userDatas = res?.rows || [];
            //               if (userDatas?.length == 1) {
            //                 setFieldsValue({ applyerID: userDatas?.[0]?.id, applyPhone: userDatas?.[0]?.phoneMobile })
            //               } else if (userDatas?.length == 0) {
            //                 setFieldsValue({ applyerID: null, applyPhone: null })
            //               }
            //               setUserData(userDatas);
            //             }
            //           })
            //         }}
            //       />
            //     );
            //   }
            // },
          },
          {
            label: '申请人',
            field: 'applyerID',
            component: 'TreeSelect',
            loading: getUserLoading,
            placeholder: '请选择',
            treeData: handleUser(userData),
            disabled: !isEditState || resObj?.checkState ? true : false,
            showArrow: !isEditState || resObj?.checkState ? false : true,
            fieldNames: { label: 'title', value: 'id' } as Record<string, any>,
            showSearch: true,
            treeNodeFilterProp: 'text',
            onSelect: (_, node) => setFieldsValue({ applyPhone: node?.phoneMobile }),
            // component: 'Render',
            // render: (text) => {
            //   if (!isEditState) {
            //     return <span>{text || '--'}</span>;
            //   } else {
            //     return (
            //       <TreeSelect
            //         loading={getUserLoading}
            //         placeholder="请选择"
            //         treeData={handleUser(userData)}
            //         disabled={!isEditState || resObj?.checkState ? true : false}
            //         showArrow={!isEditState || resObj?.checkState ? false : true}
            //         fieldNames={{
            //           label: 'title',
            //           value: 'id',
            //         }}
            //         showSearch={true}
            //         treeNodeFilterProp={'text'}
            //         treeIcon={true}
            //         onSelect={(value, node) => {
            //           setFieldsValue({ applyPhone: node?.phoneMobile })
            //         }
            //         }
            //       />
            //     );
            //   }
            // }
          },
          {
            label: '联系电话',
            field: 'applyPhone',
            component: 'Input',
            placeholder: '可修改',
            disabled: !isEditState || resObj?.checkState ? true : false,
            // disabled: true,
          },
          // {
          //   label: '采购项目名称',
          //   field: 'applyTitle',
          //   component: 'Input',
          //   placeholder: '请选择',
          //   disabled: true,
          //   required: true,
          //   contentAfter: !isEditState ? null : (
          //     <a>
          //       <SearchOutlined onClick={() => setProjectModal({ isShow: true })} />
          //     </a>
          //   ),
          // },
          {
            label: '意向公开名称',
            field: 'intentName',
            placeholder: '请输入',
            component: 'Input',
            required: true,
            colSpan: 2,
            disabled: !isEditState,
          },
          {
            label: '预计采购时间',
            field: 'expectTime',
            placeholder: '请选择',
            component: 'DatePicker',
            required: true,
            allowClear: false,
            disabled: !isEditState,
            picker: 'month',
          },
          // {
          //   label: '预算金额',
          //   field: 'expectSum',
          //   component: 'Input',
          //   placeholder: '自动带出',
          //   disabled: true,
          //   contentAfter: '元',
          // },
          {
            label: '意向公开附件',
            field: 'attachURL',
            component: 'Render',
            placeholder: '自动带出',
            slotRender: (text, record) => {
              if (isEditState) {
                return (
                  <div>
                    <UploadFormCommon
                      form={changeFromRef}
                      fileFormName={'attachURL'}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      accept={'.doc|.docx'}
                      url={'/purchaseSourceIntentController/uploadFile'}
                      downloadUrl={'/purchaseSourceIntentController/downloadFile'}
                      fileFormDelName={'delFile'}
                      uploadSuccessCallback={(attachPaths) => {
                        // setUploadUrl(attachPaths);
                      }}
                      defaultFiles={text}
                      maxFile={1}
                      hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'purchase/intent'}
                      delFunc={(delFilePath) => {
                        // setUploadUrl('');
                      }}
                    >
                      上传
                    </UploadFormCommon>
                  </div>
                );
              } else {
                return (
                  <div style={{ marginLeft: 8 }}>
                    {renderFileFunc({ record: resObj, fileName: 'attachURL', downloadAddress: '/purchaseSourceChangeController/downloadFile' })}
                  </div>
                );
              }
            },
          },
          {
            label: '采购需求概述',
            field: 'purchaseInfo',
            component: 'InputTextArea',
            placeholder: '请输入',
            colSpan: 2,
            maxLength: 200,
            showCount: true,
            required: true,
            autoSize: { minRows: 3, maxRows: 5 },
            disabled: !isEditState,
          },
          {
            label: '备注',
            field: 'remark',
            component: 'InputTextArea',
            placeholder: !isEditState ? '--' : '请输入',
            colSpan: 2,
            maxLength: 200,
            showCount: true,
            // required: true,
            autoSize: { minRows: 3, maxRows: 5 },
            disabled: !isEditState,
          },
        ],
      },
    ],
  });

  /** loading */
  const allLaoding = useMemo(() => {
    return (
      AddDisclosureLoading ||
      EditDisclosureLoading ||
      GetDetailDisclosureLoading ||
      updateApplyFlagLoading ||
      flagLoading ||
      getFlowOrgTreeLoading ||
      getPosTreeLoading ||
      getUserLoading
    );
  }, [
    GetDetailDisclosureLoading,
    EditDisclosureLoading,
    AddDisclosureLoading,
    updateApplyFlagLoading,
    flagLoading,
    getFlowOrgTreeLoading,
    getPosTreeLoading,
    getUserLoading,
  ]);

  /** 处理工作流功能 权限 */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (resObj?.state == YXGK_STATE_SHZ()) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = flowBusinessType();
    const taskHandInfo: Record<string, any> = resObj?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [resObj]);

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 底部按钮 */
  const footerBtn = (flag = false) => {
    return (
      <>
        {isEditState && flag && (
          <Button type="primary" onClick={() => submit(false)}>
            暂存
          </Button>
        )}

        {(resObj?.state == YXGK_STATE_QC() || !resObj?.state) &&
          !resObj?.checkState &&
          curRes?.['/purchaseSourceIntentController/startProcess/{starterDeptID}'] && (
            <Button type="primary" onClick={() => submit(true)}>
              提交
            </Button>
          )}

        {locationProps?.state?.returnPathName && (
          <Button danger onClick={() => closeCurrent(locationProps?.state?.returnPathName)}>
            关闭
          </Button>
        )}
      </>
    );
  };

  return (
    <div className={prefixCls + '-UpdataIntentBox'}>
      <Spin spinning={allLaoding}>
        <Card
          title={'意向公开申请'}
          className={pageStyles['page-view-cardView']}
          bodyStyle={{ padding: 0 }}
          extra={
            <Space>
              {footerBtn(true)}
              <WorkflowHndTaskBtn
                flowDetailInfo={resObj}
                flowBusinessType={flowBusinessType()}
                requestController={requestController()}
                reloadCallback={() => GetDetailDisclosureRun({ id: resObj?.id })}
                applyHeader={'apply'}
                revokeRequestUrl={'/purchaseSourceIntentController/invalid'}
                revokeRequestState={`${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}`}
                isShowRevokeStateList={[`${getTenantID()}${ILoadMapTypeAll.DISCLOSURE_STATE}1001`]}
                revokeTitle={resObj?.purchProjectName}
                revokeSuccessCallback={() => {
                  let info = { mpurchaseSourceIntents: [{ id: resObj?.id }] };
                  history.push({
                    pathname: `/purchaseSourceIntentController/edit/:${getKeyRouter()}${getKeyRouter()}`,
                    state: {
                      info: info,
                      operateType: 'Manage',
                      type: 'edit',
                      delRouterName: history?.location?.pathname,
                      returnPathName: locationProps?.state?.returnPathName,
                    },
                  });
                }}
              />
            </Space>
          }
        >
          <div className={`${prefixCls}-container`}>
            <ScrollBarLayout style={{ padding: 5 }}>
              <DescriptionsType config={config} />
            </ScrollBarLayout>
          </div>

          <div className={`${prefixCls}-footer`}>
            <Space>{footerBtn()}</Space>
          </div>
        </Card>

        {/* 工作流-----审批记录 */}
        {resObj?.paramObject?.[flowBusinessType()] && (
          <WorkflowChedkRecord
            curRes={curRes}
            dataDetailInfo={resObj}
            flowBusinessType={flowBusinessType()}
            requestController={requestController()}
            reloadPageCallback={() => {
              GetDetailDisclosureRun({ id: resObj?.id });
            }} // 刷新方法-详情方法
            revokeStateID={YXGK_STATE_QC()}
            allBtnFuncQuqry={workflowPowerAllBtn}
            tabPaneHeight={0.35}
            isCheckDrawer={true}
            isShowCollapse={isShowWorkRecord}
            changeCollapse={(val) => {
              setIsShowWorkRecord(val);
            }}
            cancelStateId={YXGK_STATE_ZF()}
            isSyncArchive={true}
          />
        )}

        {/* 工作流-----发起流程审批弹窗 */}
        {workFlowInfoObj?.showWorkFlowModal && (
          <WorkflowSwitchModal
            openVisible={workFlowInfoObj?.showWorkFlowModal}
            businessInfoObj={workFlowInfoObj?.selectFlowRows}
            requestController={requestController()}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
            category={flowBusinessType()}
            businessCategory={businessCategory()}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            reloadInfoCallback={() => {
              setFlagLoading(true);
              GetDetailDisclosureRun({ id: resObj?.id });
            }}
            openFlowChangeModal={setShowSwitchFlow}
            onClose={() => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                showWorkFlowModal: false,
              });
            }}
            replaceStrObj={{ own: 'apply', workflowType: 'category' }}
          />
        )}

        {/* 挑选流程组件 */}
        {showSwitchFlow && (
          <WorkflowNoDefaultTable
            openVisibleSwitch={showSwitchFlow}
            onCloseSwitch={closeSwitchFlowModal}
            requestController={requestController()}
            orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
            category={flowBusinessType()}
            businessCategory={businessCategory()}
            saveSelectFlowID={(flowId: string) => {
              setWorkFlowInfoObj({
                ...workFlowInfoObj,
                saveNoDefaultFlowID: flowId,
              });
            }}
            selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
          />
        )}

        {/* 选择采购项目弹窗 */}
        {ProjectModal?.isShow && (
          <UpdateIntentModal
            curRes={curRes}
            onSave={(rows) => {
              let obj = rows[0];
              // 保存对象
              setProject({
                applyID: obj?.id,
                purchProjectCode: obj?.purchProjectCode,
                purchProjectName: obj?.purchProjectName,
              });
              // 设置表单
              setFieldsValue({
                applyCode: obj?.applyCode,
                applyTitle: obj?.applyTitle,
                expectSum: formatDecimal(obj?.expectSum),
              });
            }}
            onClose={() => setProjectModal({})}
          />
        )}
      </Spin>
    </div>
  );
};

export default connect(({ navTab, baseLogin }: Record<string, any>) => ({
  navTab,
  curRes: baseLogin?.permissions,
}))(UpdateIntent);
